#include "StdAfx.h"
#include "ogrewidget.h"

OgreWidget::OgreWidget(QWidget *parent)
	: QWidget(parent), ogreEngine(NULL)
{
	ui.setupUi(this);
	this -> setFocusPolicy(Qt::StrongFocus);
	setAttribute(Qt::WA_OpaquePaintEvent);
	setAttribute( Qt::WA_PaintOnScreen);
	setAttribute( Qt::WA_NoBackground );
}

OgreWidget::~OgreWidget()
{
	ogreEngine->~Ogre3DEngine();
	destroy();
}

void OgreWidget::keyPressEvent(QKeyEvent *e)
{
	ogreEngine->getCameraHandler()->keyPressEvent(e);
}

void OgreWidget::keyReleaseEvent(QKeyEvent* e)
{
	ogreEngine->getCameraHandler()->keyReleaseEvent(e);
}

void OgreWidget::mousePressEvent(QMouseEvent *e)
{
	ogreEngine->getCameraHandler()->mousePressEvent(e);
}

void OgreWidget::mouseReleaseEvent(QMouseEvent *e)
{
	ogreEngine->getCameraHandler()->mouseReleaseEvent(e);
}

void OgreWidget::mouseMoveEvent(QMouseEvent *e)
{
	ogreEngine->getCameraHandler()->mouseMoveEvent(e);
}

void OgreWidget::wheelEvent(QWheelEvent *e)
{
	ogreEngine->getCameraHandler()->wheelEvent(e);
}

void OgreWidget::moveEvent(QMoveEvent *e)
{
    QWidget::moveEvent(e);
    
    if(e->isAccepted() && ogreEngine)
    {
		ogreEngine->getOgreWindow()->windowMovedOrResized();
        update();
    }
}

void OgreWidget::paintEvent(QPaintEvent *e)
{
	ogreEngine->getOgreRoot()->renderOneFrame();
    e->accept();
}

void OgreWidget::resizeEvent(QResizeEvent *e)
{
    QWidget::resizeEvent(e);
    
    if(e->isAccepted())
    {
        const QSize &newSize = e->size();
        if(ogreEngine)
        {
            ogreEngine->getOgreWindow()->resize(newSize.width(), newSize.height());
            ogreEngine->getOgreWindow()->windowMovedOrResized();
 
            Ogre::Real aspectRatio = Ogre::Real(newSize.width()) / Ogre::Real(newSize.height());
            ogreEngine->getCameraHandler()->setAspectRatio(aspectRatio);
        }
    }
}

void OgreWidget::showEvent(QShowEvent *e)
{
    if(!ogreEngine)
    {
		ogreEngine = new Ogre3DEngine();
		
		// init Ogre
		ogreEngine->init();

		// create render window
		ogreEngine->createOgreWindow(this);

		// setup the resource paths: materials, meshes, ...
		ogreEngine->setupResources();
		ogreEngine->loadResources();

		ogreEngine->getOgreRoot()->addFrameListener(this);

		// create the scene manager, main camera, and viewport.
		ogreEngine->createSceneManagerAndCamera(this);

		// create the scene
		ogreEngine->createScene();
	}
    
    QWidget::showEvent(e);
}

QPaintEngine *OgreWidget:: paintEngine() const
{
    return 0;
}

bool OgreWidget::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
	ogreEngine->frameRenderingQueued(evt);
	update();
	return true;
}